#ifndef _MATCHER_H__
#define _MATCHER_H__
#include "room.hpp"
#include "db.hpp"
#include "online.hpp"
#include <list>
#include <condition_variable>

template <class T>
class match_queue{
    public:
        //获取元素个数
        int size()
        {
            std::unique_lock<std::mutex> lock(_mutex);
            return _list.size();
        }
        //判断是否为空
        bool empty()
        {
            std::unique_lock<std::mutex> lock(_mutex);
            return _list.empty();
        }
        //阻塞线程
        void wait()
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond.wait(lock);
        }
        //入队数据，并唤醒线程
        void push(const T& data)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _list.push_back(data);
            _cond.notify_all();
        }
        //出队数据
        bool pop(T& data)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            if(_list.empty() == true)
            {
                return false;
            }
            data = _list.front();
            _list.pop_front();
            return true;
        }
        //移除指定数据
        bool remove(T& data)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _list.remove(data);
        }
    private:
        //⽤链表⽽不直接使⽤queue是因为我们有中间删除数据的需要
        std::list<T> _list;
        std::mutex _mutex;//保证线程安全
        std::condition_variable _cond;
};

class matcher{
    private:
        void handle_match(match_queue<uint64_t>& mq)
        {
            while(true)
            {
                //1. 判断队列⼈数是否⼤于2，<2则阻塞等待
                while(mq.size() < 2)
                {
                    std::cout << mq.size() << std::endl;
                    mq.wait();
                }
                //2. ⾛下来代表⼈数够了，出队两个玩家
                uint64_t uid1, uid2;
                bool ret = mq.pop(uid1);
                if(ret == false)
                {
                    continue;
                }
                ret = mq.pop(uid2);
                if(ret == false)
                {
                    this->add(uid1);
                    continue;
                }
                //3. 校验两个玩家是否在线，如果有⼈掉线，则要吧另⼀个⼈重新添加⼊队列
                wsserver_t::connection_ptr conn1 = _om->get_conn_from_hall(uid1);
                if(conn1.get() == nullptr)
                {
                    this->add(uid2);
                    continue;
                }

                wsserver_t::connection_ptr conn2 = _om->get_conn_from_hall(uid2);
                if(conn2.get() == nullptr)
                {
                    this->add(uid1);
                    continue;
                }
                //4. 为两个玩家创建房间，并将玩家加⼊房间中
                room_ptr rp = _rm->create_room(uid1, uid2);
                if(rp.get() == nullptr)
                {
                    this->add(uid1);
                    this->add(uid2);
                    continue;
                }
                //5. 对两个玩家进⾏响应
                Json::Value resp;
                resp["optype"] = "match_success";
                resp["result"] = true;
                std::string body;
                json_util::serialize(resp, body);
                conn1->send(body);
                conn2->send(body);
            }
        }
        void th_bronze_entry()
        {
            return handle_match(_q_bronze);
        }
        void th_silver_entry()
        {
            return handle_match(_q_silver);
        }
        void th_gold_entry()
        {
            return handle_match(_q_gold);
        }
    public:
        matcher(room_manager* rm, user_table* ut, online_manager* om)
            :_rm(rm),
            _ut(ut),
            _om(om),
            _th_bronze(std::thread(&matcher::th_bronze_entry, this)),
            _th_silver(std::thread(&matcher::th_silver_entry, this)),
            _th_gold(std::thread(&matcher::th_gold_entry, this))
        {
            DBG_LOG("游戏匹配初始化完毕...");
        }
        bool add(uint64_t uid)
        {
            //根据天梯分数来判断玩家该进入到哪一个匹配队列
            //1.根据用户id，获取玩家信息
            Json::Value user;
            bool ret = _ut->select_by_id(uid, user);

            if(ret == false)
            {
                DBG_LOG("获取玩家：%d 信息失败!", uid);
                return false;
            }
            int score = user["score"].asInt();
            std::cout << user["username"].asString() << std::endl;
            //2.添加到指定的队列中
            if(score < 2000)
            {
                _q_bronze.push(uid);
            }
            else if(score >= 3000)
            {
                _q_gold.push(uid);
            }
            else
            {
                _q_silver.push(uid);
            }
            return true;
        }
        bool del(uint64_t uid)
        {
            Json::Value user;
            bool ret = _ut->select_by_id(uid, user);
            if(ret == false)
            {
                DBG_LOG("获取玩家：%d 信息失败!", uid);
                return false;
            }
            int score = user["score"].asInt();
            //2.移除指定队列的用户
            if(score < 2000)
            {
                _q_bronze.remove(uid);
            }
            else if(score >= 3000)
            {
                _q_gold.remove(uid);
            }
            else
            {
                _q_silver.remove(uid);
            }
            return true;
        }
    private:
        match_queue<uint64_t> _q_bronze;//青铜
        match_queue<uint64_t> _q_silver;//白银
        match_queue<uint64_t> _q_gold;//黄金
        std::thread _th_bronze;
        std::thread _th_silver;
        std::thread _th_gold;
        room_manager* _rm;
        user_table* _ut;
        online_manager* _om;
};
#endif